package cn.cqvie.controller;

import cn.cqvie.common.R;
import cn.cqvie.utils.EmailCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
public class Common {
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${Img.path}")
    private String path;
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //输入流读取文件
        FileInputStream inputStream=new FileInputStream(new File(path)+"\\"+name);
        //通过输出流将读取的文件写回浏览器
        ServletOutputStream outputStream=response.getOutputStream();
        //设置文件的返回格式为jpg
        response.setContentType("image/jpeg");
        int length;
        byte[] bytes=new byte[1024];
        while((length=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,length);
            outputStream.flush();
        }
        inputStream.close();
        outputStream.close();
    }
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        File f=new File(path);
        if(!f.exists()){
            f.mkdir();
        }
        File f2=new File(path+"\\"+filename);
        if(!f2.exists()){
            file.transferTo(new File(path + "\\" + filename));
        }
        return R.success(filename);
    }
    @PostMapping
    public R<String> getCode(@RequestBody String code) throws Exception {
        System.out.println(code);
        EmailCode emailCode = new EmailCode();
        String c = emailCode.getCode(code);
        redisTemplate.opsForValue().set(code,c,5, TimeUnit.MINUTES);
        return R.success(c);
    }
}
